package com.droidathletics.boundary.macrocycles;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.StringTokenizer;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.droidathletics.R;
import com.droidathletics.boundary.MainMenu;
import com.droidathletics.control.ManageMacrocycle;
import com.droidathletics.entity.Competition;
import com.droidathletics.entity.Macrocycle;

public class EditMacrocycle extends Activity {

	 // the callback received when the user "sets" the date in the dialog
   private DatePickerDialog.OnDateSetListener mInitialDateSetListener =
           new DatePickerDialog.OnDateSetListener() {

               public void onDateSet(DatePicker view, int year, 
                                     int monthOfYear, int dayOfMonth) {
                   initialDateYear = year;
                   initialDateMonth = monthOfYear;
                   initialDateDay = dayOfMonth;
                   updateIDateField();
               }
           };
   private DatePickerDialog.OnDateSetListener mFinalDateSetListener =
           new DatePickerDialog.OnDateSetListener() {

               public void onDateSet(DatePicker view, int year, 
                                     int monthOfYear, int dayOfMonth) {
                   finalDateYear = year;
                   finalDateMonth = monthOfYear;
                   finalDateDay = dayOfMonth;
                   updateFDateField();
               }
           };
   private void updateIDateField(){
   	initialDate.setText(new StringBuilder()
	        .append(initialDateMonth + 1).append("/")
	        .append(initialDateDay).append("/")
	        .append(initialDateYear));
   }
   private void updateFDateField(){
   	finishingDate.setText(new StringBuilder()
	        .append(finalDateMonth + 1).append("/")
	        .append(finalDateDay).append("/")
	        .append(finalDateYear));
   }
	@Override
	public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.create_macrocycle);
       
       Bundle b = getIntent().getExtras();
       int position = b.getInt("key");
       
       final Macrocycle editedMacrocycle = (Macrocycle) MainMenu.listMacrocycles.getAdapter().getItem(position); 
       
       manageMacrocycle = MainMenu.manageMacrocycle;
       
       name = (EditText) findViewById(R.id.fieldCreateMacrocycleName);
       team = (EditText) findViewById(R.id.fieldCreateMacrocycleTeam);
       category = (EditText) findViewById(R.id.fieldCreateMacrocycleCategory);
       competition = (EditText) findViewById(R.id.fieldCreateMacrocycleCompetition);
       initialDate = (EditText) findViewById(R.id.fieldCreateMacrocycleInitialDate);
       finishingDate = (EditText) findViewById(R.id.fieldCreateMacrocycleFinishingDate);
       branch = (Spinner) findViewById(R.id.spinnerCMacrocycleBranch);
       
       errorData = (TextView) findViewById(R.id.textViewCreateMacrocycleError);
       
       saveButton = (Button) findViewById(R.id.createMacrocycleSave);
       
       saveButton.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
           	updateDates();
           	String errorResult = manageMacrocycle.updateMacrocycle(editedMacrocycle,
           			name.getText().toString(), 
           			dayStart, 
           			monthStart, 
           			yearStart, 
           			dayEnd, 
           			monthEnd, 
           			yearEnd, 
           			team.getText().toString(), 
           			branch.getSelectedItem().toString(), 
           			category.getText().toString(), 
           			competition.getText().toString());
           	
           	if ( errorResult == "")
           	{
           		finish();
               	Intent intent = new Intent(EditMacrocycle.this, MainMenu.class);
                startActivity(intent);
           	}
           	else
           	{
           		errorData.setText(errorResult);
           	}

           }
       });
       
       pickIDateButton = (Button)findViewById(R.id.buttonCMacroInitial); 
       
       pickIDateButton.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
               showDialog(INITIAL_DATE_DIALOG_ID);
           }
       });
       
       pickFDateButton = (Button)findViewById(R.id.buttonCMacroFinal); 
       
       pickFDateButton.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
               showDialog(END_DATE_DIALOG_ID);
           }
       });
    
       name.setText(editedMacrocycle.getName());
       team.setText(editedMacrocycle.getTeamName());
       category.setText(editedMacrocycle.getCategory());
       competition.setText(editedMacrocycle.getCompetition());
       initialDate.setText(new StringBuilder()
	        .append(editedMacrocycle.getStartDate().getMonth()).append("/")
	        .append(editedMacrocycle.getStartDate().getDay()).append("/")
	        .append(editedMacrocycle.getStartDate().getYear()));
       finishingDate.setText(new StringBuilder()
       .append(editedMacrocycle.getEndDate().getMonth()).append("/")
       .append(editedMacrocycle.getEndDate().getDay()).append("/")
       .append(editedMacrocycle.getEndDate().getYear()));
       branch.setSelection(getBranchPosition(editedMacrocycle.getBranch()));
       
    // get the current date
       final Calendar c = Calendar.getInstance();
       initialDateYear = finalDateYear = c.get(Calendar.YEAR);
       initialDateMonth = finalDateMonth= c.get(Calendar.MONTH);
       initialDateDay = finalDateDay = c.get(Calendar.DAY_OF_MONTH);
	}
	
	private int getBranchPosition(String branch){
		String[] branches = getResources().getStringArray(R.array.branches);
		for(int i=0;i<branches.length;i++){
			if(branch.equals(branches[i])){
				return i;
			}
		}
		return 0;
	}
	
	@Override
   public void onBackPressed() {
		finish();
        Intent intent = new Intent(EditMacrocycle.this, MainMenu.class);
        startActivity(intent);
	    return;
   }
	
	@Override
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    case INITIAL_DATE_DIALOG_ID:
	        return new DatePickerDialog(this,
	                    mInitialDateSetListener,
	                    initialDateYear, initialDateMonth, initialDateDay);
	    case END_DATE_DIALOG_ID:
	    	return new DatePickerDialog(this,
                   mFinalDateSetListener,
                   finalDateYear, finalDateMonth, finalDateDay);
	    }
	    return null;
	}
	
	private void updateDates(){
		StringTokenizer tokensStartDate = new StringTokenizer(initialDate.getText().toString(),"/");
		dayStart = tokensStartDate.nextToken();
		monthStart = tokensStartDate.nextToken();
		yearStart = tokensStartDate.nextToken();
		StringTokenizer tokensEndDate = new StringTokenizer(finishingDate.getText().toString(),"/");
		dayEnd = tokensEndDate.nextToken();
		monthEnd = tokensEndDate.nextToken();
		yearEnd = tokensEndDate.nextToken();
	}
	
	static final int INITIAL_DATE_DIALOG_ID = 0;
	static final int END_DATE_DIALOG_ID = 1;
	private Button saveButton,pickIDateButton,pickFDateButton;
	private int initialDateYear,initialDateMonth,initialDateDay;
	private int finalDateYear,finalDateMonth,finalDateDay;
	private ManageMacrocycle manageMacrocycle;
	private EditText name; 
	private EditText team;
	private EditText category;
	private EditText competition;
	private EditText initialDate;
	private EditText finishingDate;
	private Spinner branch;
	private TextView errorData;
	private String dayStart;
	private String monthStart;
	private String yearStart;
	private String dayEnd;
	private String monthEnd;
	private String yearEnd;
	
}